//
//  HWNavigationController.m
//  OCDome
//
//  Created by 李含文 on 2020/10/14.
//  Copyright © 2020 李含文. All rights reserved.
//

#import "HWNavigationController.h"
#import <objc/runtime.h>

#define kDefaultBackImageName @"back"

@implementation UIViewController (HWNavigationExtension)

/// 修改导航栏颜色
- (void)hw_switchNavColor:(UIColor *)color {
    UIColor *titleColor;
    titleColor = (color == [UIColor whiteColor]) ? [UIColor blackColor] : [UIColor whiteColor];
    if (@available(iOS 13.0, *)) {
        [UIApplication sharedApplication].statusBarStyle = (color == [UIColor whiteColor]) ? UIStatusBarStyleDarkContent : UIStatusBarStyleLightContent;//UIStatusBarStyleDarkContent:黑色 UIStatusBarStyleLightContent:白色
    } else {
        [UIApplication sharedApplication].statusBarStyle = (color == [UIColor whiteColor]) ? UIStatusBarStyleDefault : UIStatusBarStyleLightContent;
    }
    UINavigationBar *navBar = self.navigationController.navigationBar;
    //导航栏背景颜色转图片
    [navBar setBackgroundImage:[self imageWithColor:color size:CGSizeMake(UIScreen.mainScreen.bounds.size.width, 88)] forBarMetrics:UIBarMetricsDefault];
//    navBar.shadowImage = [UIImage new]; // 去掉底部线条
    // 标题-文字颜色
    NSDictionary *dict = @{NSForegroundColorAttributeName:titleColor, NSFontAttributeName:[UIFont boldSystemFontOfSize:18]};
    navBar.titleTextAttributes = dict;
    navBar.barTintColor = titleColor;
    navBar.tintColor = titleColor;
}
- (void)hw_removeNavBarBottomBlackLine {
    UINavigationBar *navBar = self.navigationController.navigationBar;
    navBar.shadowImage = [UIImage new]; // 去掉底部线条
}
- (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size {
    if (!color || size.width <= 0 || size.height <= 0) return nil;
    CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

// MARK: - 快速添加返回按钮 并让边缘手势生效
- (void)hw_customBackButton {
    if (!self.navigationController) {return;} // 如果没有导航控制器 什么都不做做 防呆
    UIImage *image = [UIImage imageNamed:kDefaultBackImageName];
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:image style:(UIBarButtonItemStyleDone) target:self action:@selector(hw_backButtonClick)];
    if (@available(iOS 11.0, *)) {
        leftBarButtonItem.imageInsets = UIEdgeInsetsMake(2, -8, 0, 0);
        self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    } else {
        UIBarButtonItem *nagetiveSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemFixedSpace) target:nil action:nil];
        nagetiveSpacer.width = -8; //这个值可以根据自己需要自己调整
        self.navigationItem.leftBarButtonItems = @[leftBarButtonItem, leftBarButtonItem];
    }
    if (self.hw_navigationController.viewControllers.count > 1 && self.hw_navigationController.interactivePopGestureRecognizer.enabled == YES) { // 自定义返回按钮 回复边缘返回手势
        self.hw_navigationController.interactivePopGestureRecognizer.delegate = self.hw_navigationController;
    }
}

- (void)hw_backButtonClick {
    if ([self respondsToSelector:@selector(hw_navigationShouldPopOnBackButton)] && ![self hw_navigationShouldPopOnBackButton]) {
        return;
    }
    if (!self.hw_navigationController) { // 普通的 没有使用当前导航栏的
        if (self.navigationController.childViewControllers.count == 1) {
            [self dismissViewControllerAnimated:YES completion:nil];
        } else {
            [self.navigationController popViewControllerAnimated:YES];
        }
        return;
    }
    if (self.hw_navigationController.childViewControllers.count == 1) { // 因为给每个控制器添加了一层导航控制器 所以这里有2个navigationController
        [self dismissViewControllerAnimated:YES completion:nil];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (HWNavigationController *)hw_navigationController {
    return objc_getAssociatedObject(self, _cmd);
}

- (void)setHw_navigationController:(HWNavigationController *)navigationController {
    objc_setAssociatedObject(self, @selector(hw_navigationController), navigationController, OBJC_ASSOCIATION_ASSIGN);
}

- (void)hw_popToViewControllerWithName:(NSString *)name {
    __weak typeof(self) weakSelf = self;
    if (!self.hw_navigationController) { // 普通的 没有使用当前导航栏的
       [self.navigationController.viewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
           __strong __typeof(weakSelf) strongSelf = weakSelf;
           if ([obj isKindOfClass:NSClassFromString(name)]) {
               [strongSelf.navigationController popToViewController:obj animated:YES];
               *stop = YES;
               return;
           }
       }];
        return;
    } else {
        [self.hw_navigationController.viewControllers enumerateObjectsUsingBlock:^(__kindof HWWrapViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            __strong __typeof(weakSelf) strongSelf = weakSelf;
            if ([obj.rootViewController isKindOfClass:NSClassFromString(name)]) {
                [strongSelf.hw_navigationController popToViewController:obj animated:YES];
                *stop = YES;
                return;
            }
        }];
    }
}


@end

@interface HWWrapViewController()
+ (HWWrapViewController *)wrapViewControllerWithViewController:(UIViewController *)viewController;
@end

#pragma mark - HWWrapNavigationController
@interface HWWrapNavigationController : UINavigationController

@end

@implementation HWWrapNavigationController

- (UIViewController *)popViewControllerAnimated:(BOOL)animated {
    return [self.navigationController popViewControllerAnimated:animated];
}

- (NSArray<UIViewController *> *)popToRootViewControllerAnimated:(BOOL)animated {
    return [self.navigationController popToRootViewControllerAnimated:animated];
}

- (NSArray<UIViewController *> *)popToViewController:(UIViewController *)viewController animated:(BOOL)animated {
    HWNavigationController *hw_navigationController = viewController.hw_navigationController;
    NSInteger index = [hw_navigationController.hw_viewControllers indexOfObject:viewController];
    return [self.navigationController popToViewController:hw_navigationController.viewControllers[index] animated:animated];
}

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
    viewController.hw_navigationController = (HWNavigationController *)self.navigationController;
    if (self.viewControllers.count > 0) {
        if (self.viewControllers.count == 1) {
            viewController.hidesBottomBarWhenPushed = YES;
        }
    } else {
        viewController.hidesBottomBarWhenPushed = NO;
    }
    HWWrapViewController *wrapVC = [HWWrapViewController wrapViewControllerWithViewController:viewController];
    [viewController hw_customBackButton]; 
    [self.navigationController pushViewController:wrapVC animated:animated];
}

-(void)dismissViewControllerAnimated:(BOOL)flag completion:(void (^)(void))completion{
    [self.navigationController dismissViewControllerAnimated:flag completion:completion];
    self.viewControllers.firstObject.hw_navigationController = nil;
}

@end

#pragma mark - HWWrapViewController
static NSValue *hw_tabBarRectValue;

@implementation HWWrapViewController

+ (HWWrapViewController *)wrapViewControllerWithViewController:(UIViewController *)viewController {
    HWWrapNavigationController *wrapNavController = [[HWWrapNavigationController alloc] init];
    wrapNavController.view.backgroundColor = UIColor.clearColor;
    wrapNavController.viewControllers = @[viewController];
    HWWrapViewController *wrapViewController = [[HWWrapViewController alloc] init];
    wrapViewController.view.backgroundColor = UIColor.clearColor;
    [wrapViewController.view addSubview:wrapNavController.view];
    [wrapViewController addChildViewController:wrapNavController];
    return wrapViewController;
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    if (self.tabBarController && !hw_tabBarRectValue) {
        hw_tabBarRectValue = [NSValue valueWithCGRect:self.tabBarController.tabBar.frame];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (self.tabBarController && [self rootViewController].hidesBottomBarWhenPushed) {
        self.tabBarController.tabBar.frame = CGRectZero;
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.translucent = YES;
    if (self.tabBarController && !self.tabBarController.tabBar.hidden && hw_tabBarRectValue) {
        self.tabBarController.tabBar.frame = hw_tabBarRectValue.CGRectValue;
    }
}

- (BOOL)hidesBottomBarWhenPushed {
    return [self rootViewController].hidesBottomBarWhenPushed;
}

- (UITabBarItem *)tabBarItem {
    return [self rootViewController].tabBarItem;
}

- (NSString *)title {
    return [self rootViewController].title;
}

- (UIViewController *)childViewControllerForStatusBarStyle {
    return [self rootViewController];
}

- (UIViewController *)childViewControllerForStatusBarHidden {
    return [self rootViewController];
}

- (UIViewController *)rootViewController {
    HWWrapNavigationController *wrapNavController = self.childViewControllers.firstObject;
    return wrapNavController.viewControllers.firstObject;
}

@end

@interface HWNavigationController ()<UINavigationControllerDelegate, UIGestureRecognizerDelegate>

@end

@implementation HWNavigationController

- (instancetype)initWithRootViewController:(UIViewController *)rootViewController {
    if (self = [super initWithRootViewController:rootViewController]) {
        rootViewController.hw_navigationController = self;
        self.viewControllers = @[[HWWrapViewController wrapViewControllerWithViewController:rootViewController]];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        self.viewControllers.firstObject.hw_navigationController = self;
        self.viewControllers = @[[HWWrapViewController wrapViewControllerWithViewController:self.viewControllers.firstObject]];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavigationBarHidden:YES];
    self.interactivePopGestureRecognizer.delegate = (id<UIGestureRecognizerDelegate>)self;
}

//MARK: 按钮控制
// 系统按钮点击来此方法
//- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item {
//    NSLog(@"按钮来了");
//    if ([self.viewControllers count] < [navigationBar.items count]) {
//        return YES;
//    }
//    BOOL shouldPop = YES;
//    UIViewController* vc = [self topViewController];
//    if([vc respondsToSelector:@selector(hw_navigationShouldPopOnBackButton)]) {
//        shouldPop = [vc hw_navigationShouldPopOnBackButton];
//    }
//    if(shouldPop) {
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [self popViewControllerAnimated:YES];
//        });
//    } else {
//        for(UIView *subview in [navigationBar subviews]) {
//            if(0. < subview.alpha && subview.alpha < 1.) {
//                [UIView animateWithDuration:.25 animations:^{
//                    subview.alpha = 1.;
//                }];
//            }
//        }
//    }
//    return NO;
//}

#pragma mark - UIGestureRecognizerDelegate
//MARK: 手势控制
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    if (self.childViewControllers.count == 1) { // 避免第一层出现问题
        return NO;
    }
    NSLog(@"手势来了");
    UIViewController *vc = [self topViewController];
    if (gestureRecognizer == self.interactivePopGestureRecognizer) {
        NSLog(@"%@", vc);
        if ([[self topViewController] isKindOfClass:[HWWrapViewController class]]) {
            UIViewController *vc = ((HWWrapViewController*)[self topViewController]).rootViewController;
            if([vc respondsToSelector:@selector(hw_navigationShouldPopOnBackButton)]) {
                return [vc hw_navigationShouldPopOnBackButton];
            }
        }
    }
    return YES;
}

#pragma mark - Getter
- (NSArray *)hw_viewControllers {
    NSMutableArray *viewControllers = [NSMutableArray array];
    for (HWWrapViewController *wrapViewController in self.viewControllers) {
        [viewControllers addObject:wrapViewController.rootViewController];
    }
    return viewControllers.copy;
}

@end
